package com.xuecheng.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.auth.service.AuthService;
import com.xuecheng.ucenter.mapper.XcMenuMapper;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcMenu;
import com.xuecheng.ucenter.model.po.XcUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import springfox.documentation.spring.web.json.Json;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author:王亚栋
 * @Date:2023/8/13 20:32
 * @Version:1.0
 * 自定义一个UserDetail
 */
@Component
@Slf4j(topic = "plus-auth-UserDetailServiceImpl")
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private XcUserMapper xcUserMapper;

    @Autowired
    ApplicationContext applicationContext;

    @Autowired
    private XcMenuMapper xcMenuMapper;

    /**
     * 通过用户名查询用户信息
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //将传入的Json转为AuthParamDto对象
        AuthParamsDto authParamsDto = null;

        try {

           authParamsDto = JSON.parseObject(username,AuthParamsDto.class);

           log.info("authParamsDto--:{}",authParamsDto);


        }catch (Exception e){

            log.error("认证请求不符合项目要求:{}",username);

            throw new RuntimeException("请求认证参数不符合要求！");
        }

        //认证类型
        String authType = authParamsDto.getAuthType();

        // 根据认证类型从Spring容器取出指定的Bean
        String beanName = authType + "_authService";

        AuthService authService = applicationContext.getBean(beanName, AuthService.class);

        //调用统一Execute方法
        XcUserExt xcUserExt = authService.execute(authParamsDto);

        //封装 XcUserExt 为 UserDetails对象
        //根据UserDetails对象生成令牌
        UserDetails userPrincipal = getUserPrincipal(xcUserExt);

        return userPrincipal;
    }

    /**
     * 查询用户信息
     * @param user 用户Id，主键
     * @return 用户信息
     */
    private UserDetails getUserPrincipal(XcUserExt user){

        String password = user.getPassword();

        //用户的权限
        String[] authorities = null;

        //根据用户Id查询用户的权限信息
        List<XcMenu> xcMenus = xcMenuMapper.selectPermissionByUserId(user.getId());

        if (xcMenus.size() > 0){

            List<String> permissions = new ArrayList<>();

            xcMenus.forEach(m -> {
                //拿到用户拥有的权限标识符
                permissions.add(m.getCode());
            });

            //将permissions转为数组
            authorities =  permissions.toArray(new String[0]);
        }

        user.setPassword(null);

        //将用户信息转为Json
        String xcUserjsonStr = JSON.toJSONString(user);

        UserDetails userDetails = User.withUsername(xcUserjsonStr).password(password).authorities(authorities).build();

        return userDetails;

    }
}
